package com.lykj.modules.shop.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.lykj.common.cache.ParamCache;
import com.lykj.core.boot.ctrl.LykjController;
import com.lykj.core.boot.request.LykjHttpServletRequestWrapper;
import com.lykj.core.cache.utils.CacheUtil;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.api.R;
import com.lykj.core.tool.utils.Func;
import com.lykj.modules.job.jobhandler.ShsyTaskJob;
import com.lykj.modules.shop.entity.StoreCalendar;
import com.lykj.modules.shop.entity.StoreProduct;
import com.lykj.modules.shop.entity.UserOrder;
import com.lykj.modules.shop.mapper.UserOrderMapper;
import com.lykj.modules.shop.service.*;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.entity.Param;
import com.lykj.modules.system.entity.User;
import com.lykj.modules.system.service.ParamService;
import com.lykj.modules.system.service.UserService;
import com.wx.sdk.MyConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.lykj.core.cache.constant.CacheConstant.PARAM_CACHE;

/**
 * 商城首页 控制器
 *
 * @author cxl
 * @since 2022-01-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("lykj-shop/xcxpay/kdcnb/pay")
@Api(value = "商城首页", tags = "商城首页")
public class PayController extends LykjController {
    private final UserOrderMapper userOrderMapper;
    private final ZnApiUtils znApiUtils;
    private final UserBillService userBillService;
    private final UserService userService;

	/**
	 * 小程序回调支付结果
	 */
	@PostMapping("/shawanying")
	public void checkPayState(HttpServletRequest request, HttpServletResponse response) throws Exception {
	    String ojbk="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	    try{
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(ojbk.getBytes());
            out.flush();
            out.close();
        }finally {
	        response.getOutputStream().close();
        }


        //禁止回调
        synchronized (this) {
            String str = getXmlData(request);
            System.out.println("==========支付结果str===================="+str);
            MyConfig config = new MyConfig();
            WXPay wxpay = new WXPay(config);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(str);  // 转换成map

            System.out.println("==========支付结果===================="+notifyMap);
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
                System.out.println("==========支付结果成功===================="+notifyMap);

                BigDecimal temp=BigDecimal.valueOf(Integer.parseInt(notifyMap.get("total_fee")+"")).divide(BigDecimal.valueOf(100));
                // 签名正确
                // 进行处理。
                // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
                UserOrder userOrder = userOrderMapper.selectById(Long.parseLong(notifyMap.get("out_trade_no")));
                if (userOrder.getPayPrice().compareTo(temp)!=0){
                    System.err.println("==========支付结果跟订单金额不匹配===================="+notifyMap);
                    userOrder.setPayPrice(temp);
                }
                userOrder.setStatus(-1);
                userOrderMapper.updateById(userOrder);
                User user = userService.getById(userOrder.getUserId());
                try {
                    userBillService.insertBill(
                            user.getTenantId(),
                            user.getId(),
                            0L,
                            userOrder.getId(),
                            0,//0转出1转入
                            userOrder.getPayPrice(),
                            BigDecimal.ZERO,
                            "小程序支付购买",
                            0,//0现金1积分2贡献值
                            6,//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
                            "平台余额购买,现金[" + userOrder.getPayPrice() + "],手续费[" + BigDecimal.ZERO + "],实际金额[" + userOrder.getPayPrice() + "]"
                            //,余额[" + userBalance + "]
                    );

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try{
                    if(temp.compareTo(BigDecimal.valueOf(299)) > -1) {
                        znApiUtils.brokerageTwoStatus(userOrder.getTenantId(), user.getAccount());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                System.out.println("==========支付结果失败===================="+notifyMap);
                // 签名错误，如果数据里没有sign字段，也认为是签名错误
            }
        }
        Object parse = JSONObject.parse("{\n" +
                "      'mpserverlessComposedResponse': true,\n" +
                "      'statusCode': 200,\n" +
                "      'headers': {\n" +
                "        'content-type': 'text/xml;charset=utf-8'\n" +
                "      },\n" +
                "      'body': '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'\n" +
                "    }");
	}

    private String getXmlData(HttpServletRequest request) {
        request= LykjHttpServletRequestWrapper.getOrgRequest(request);
	    //GBK
        StringBuffer sb = new StringBuffer();
        InputStream is = null;
        BufferedReader br = null;
        try {
            is = request.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "GBK"));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


}
